<template>
   <el-dialog
      :title="areaData.title"
      v-model="dialogVisible"
      append-to-body
      draggable
      destroy-on-close
      @close="handleClose()"
      @open="handleOpen()"
   >
      <el-form :model="queryParams" ref="serviceRef" :inline="true" :rules="rules" class="shop-form" label-width="110px">
         <el-form-item label="门店名称" prop="shopName">
            <el-input
               v-model="queryParams.shopName"
               placeholder="请输入门店名称"
               clearable
            />
         </el-form-item>

         <el-form-item label="店长姓名" prop="shopManagerName">
            <el-input
               v-model="queryParams.shopManagerName"
               placeholder="请输入店长姓名"
               clearable
            />
         </el-form-item>

         <el-form-item label="联系方式" prop="phonenumber">
            <el-input
               v-model.number="queryParams.phonenumber"
               placeholder="请输入联系方式"
               clearable
               maxlength="11"
            />
         </el-form-item>

         <el-form-item label="地址" prop="address">
            <el-input
               v-model="queryParams.address"
               placeholder="请输入门店地址"
               clearable
            />
         </el-form-item>

         <el-form-item label="所属服务区" prop="serviceId">
            <el-tree-select
               v-model="queryParams.serviceId"
               :data="deptTreeData"
               :props="{ value: 'id', label: 'label', children: 'children' }"
               :render-after-expand="false"
               show-checkbox
               value-key="id"
               check-strictly
               placeholder="请选择所属服务区"
               :disabled="!!areaData.serviceId"
               @check="handleChange"
            />
         </el-form-item>

         <el-form-item prop="provinceCode" label="所属行政区">
            <el-select
               v-model="queryParams.provinceCode"
               placeholder="请选择行政区"
               clearable
               @change="handleSelect"
            >
               <el-option
                  v-for="item in provinces"
                  :key="item.code"
                  :label="item.label"
                  :value="item.code"
               />
            </el-select>
         </el-form-item>
         
         <el-form-item label="营业时间" prop="businessHours" class="business-time">
            <el-time-select
               v-model="queryParams.startTime"
               :max-time="endTime"
               class="mr-4 with-half"
               placeholder="Start time"
               start="00:00"
               step="00:10"
               end="24:00"
            />
            <el-time-select
               v-model="queryParams.endTime"
               :min-time="startTime"
               class="mr-4 with-half"
               placeholder="End time"
               start="00:00"
               step="00:10"
               end="24:00"
            />
         </el-form-item>

         <el-form-item label="邮箱" prop="email">
            <el-input
               v-model="queryParams.email"
               placeholder="请输入邮箱"
               clearable
            />
         </el-form-item>

         <el-form-item label="门店人数(个)" prop="employeeNum">
            <el-input-number v-model="queryParams.employeeNum" placeholder="请输入门店人数" :min="0" class="with-cover"></el-input-number>
         </el-form-item>
         
         <el-form-item label="门店面积(㎡)" prop="shopArea">
            <el-input v-model="queryParams.shopArea" placeholder="请输入门店面积">
               <template #append>㎡</template>
            </el-input>
         </el-form-item>
         <el-form-item label="设备数(个)" prop="deviceNum">
            <el-input-number v-model="queryParams.deviceNum" placeholder="请输入门店设备数" :min="0" class="with-cover"></el-input-number>
         </el-form-item>
         
         <el-form-item label="用户数(个)" prop="customerNum">
            <el-input-number v-model="queryParams.customerNum" placeholder="请输入门店用户数" :min="0" class="with-cover"></el-input-number>
         </el-form-item>
      </el-form> 
      <template #footer>
         <div class="dialog-footer btn-wrap mt-50">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="emit('close')">取 消</el-button>
         </div>
      </template>
   </el-dialog>
</template>
<script setup name="Notice">
import { getShopInfo,addShop,updateShop } from "@/api/system/shop";
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const { provinces} = proxy.useDict("provinces");
const emit = defineEmits(["close",'submitSuccess'])
const props = defineProps({
   areaData: { 
      type: Object, 
      default: () => {} 
   },
})

const checkBusinessHours = (rule, value, callback) => {
  if (!queryParams.value.startTime && !queryParams.value.endTime) {
    callback(new Error('请选择门店营业时间'))
  } else {
   proxy.$refs["serviceRef"].clearValidate(['businessHours'])
   callback()
  }
}
const data = reactive({
  queryParams: {
   serviceId:"",
   serviceName:"",
   shopName:""  ,
   shopManagerName:"",
   phonenumber:"",
   provinceCode:"",
   provinceName:"",
   address:"",
   startTime:"",
   endTime:"",
   businessHours:"",
   employeeNum:"",
   shopArea:"",
   email:"",
   deviceNum:"",
   customerNum:""
  },
  rules: {
   serviceId:[{ required: true, message: "请选择所属服务区", trigger: "change" }],
   shopName: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
   shopManagerName: [{ required: true, message: "请输入店长姓名 ", trigger: "blur" }],
   phonenumber: [
      { required: true,message: "请输入店长联系方式", trigger: "blur" },
      { type: 'number',pattern: /^[0-9]*$/,message: "输入联系方式格式不对", trigger:["blur", "change"] }
   ],
   provinceCode:[{ required: true, message: "请选择所属行政区", trigger: "change" }],
   address: [{ required: true, message: "请输入门店地址", trigger: "blur" }],
   businessHours: [{ required: true,validator: checkBusinessHours, message: "请选择门店营业时间", trigger: "change" }],
   employeeNum: [{ required: true, message: "请输入门店人数", trigger: "change" }],
   shopArea: [
      { required: true,message: "请输入服务区面积", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: "请输入数字或者和小数", trigger: "blur" },
   ],
   email: [{ required: true,type: 'email', message: "请输入联系邮箱", trigger: ["blur", "change"] }],
   deviceNum: [{ required: true, message: "请输入门店设备数", trigger: "change" }],
   customerNum: [{ required: true, message: "请输入门店用户数", trigger: "change" }],
  },
});

const { queryParams, rules } = toRefs(data);

const dialogVisible = computed({
   set:(val) => {
      emit("close")
   },
   get:() =>{
      return props?.areaData.open
   }
})

const handleChange = (node) =>{
   queryParams.value.serviceName = node.label;
   queryParams.value.serviceId = node.id;
}

const handleSelect = (val) =>{
   queryParams.value.provinceCode = val;
   queryParams.value.provinceName = provinces.value?.find(ele => ele.code == val)?.label;
}

const handleClose = ()=> {
   proxy.resetForm("serviceRef");
}
const handleOpen = ()=> {
   proxy.resetForm("serviceRef");
   if(!props.areaData.shopId){
      return
   }
   getInfo()
}

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["serviceRef"].validate(valid => {
    if (valid) {
      queryParams.value.businessHours = queryParams.value.startTime + "-" + queryParams.value.endTime;
      if (props.areaData.shopId) {
         updateShop(queryParams.value).then(response => {
            if(response.code == 200){
               emit("submitSuccess")
               proxy.$modal.msgSuccess("修改店铺成功");
            }
            else{
               proxy.$modal.msgError(response?.msg || "修改店铺失败，请稍后重试!");
            }
         }).catch(() => {
            proxy.$modal.msgError("系统错误，请稍后重试!");
         })
      } else {
         addShop(queryParams.value).then(response => {
            if(response.code == 200){
               emit("submitSuccess")
               proxy.$modal.msgSuccess("新增店铺成功");
            }
            else{
               proxy.$modal.msgError(response?.msg || "新增店铺失败，请稍后重试!");
            }
         }).catch(() => {
            proxy.$modal.msgError("系统错误，请稍后重试!");
         })
      }
    }
  });
}

const getInfo = () =>{
   getShopInfo(props.areaData.shopId).then(response => {
      if(response.code == 200){
         queryParams.value = response.data;
         queryParams.value.phonenumber = Number(queryParams.value.phonenumber);
         queryParams.value.startTime = queryParams.value?.businessHours?.split("-")[0] || "";
         queryParams.value.endTime = queryParams.value?.businessHours?.split("-")[1] || "";
         queryParams.value.provinceCode = Number(queryParams.value?.provinceCode);
      }
      else{
         proxy.$modal.msgError(response?.msg || "获取配置信息失败，请稍后重试!");
         proxy.resetForm("serviceRef");
      }
   }).catch(() => {
      proxy.$modal.msgError("系统错误，请稍后重试!");
   })
}

const deptTreeData = computed(()=>{
   return useUserStore().deptTreeData
})
</script>

<style lang="scss" scoped>
   .shop-form{
      .el-form-item {
         width: 49%;
         margin-right: 0;
      }
      .business-time{
         :deep(.el-form-item__content){
            display: flex;
            justify-content: space-between;
         }
      }
   }
   .btn-wrap{
      text-align: center
   }
</style>
